﻿using System.Web.Http;

namespace Sidvall.Web.IO
{
    public class ContentInfo
    {
        #region IsMultipartRequest

        public bool IsMultipartRequest
        {
            get
            {
                return (this.Ranges != null && this.Ranges.Count > 1);
            }
        }

        #endregion
        #region IsRangeRequest

        public bool IsRangeRequest
        {
            get
            {
                return (this.Ranges != null && this.Ranges.Count > 0);
            }
        }

        #endregion
        #region Ranges

        private ByteRangeCollection _Ranges;
        public ByteRangeCollection Ranges
        {
            get
            {
                return _Ranges;
            }
            private set
            {
                _Ranges = value;
            }
        }

        #endregion

        #region Parse

        public static ContentInfo Parse(long entityLength, int length, long position)
        {
            var item = new ContentInfo();
            if (length < entityLength)
            {
                if (position < 0)
                    position = 0;
                item.Ranges = new ByteRangeCollection();
                item.Ranges.Add(position, position + length - 1);
            }
            return item;
        }
        public static ContentInfo Parse(long entityLength, System.Net.Http.Headers.RangeHeaderValue rangeHeader)
        {
            var item = new ContentInfo();
            if ((rangeHeader != null) && (rangeHeader.Ranges.Count != 0))
            {
                item.Ranges = new ByteRangeCollection();
                foreach (var range in rangeHeader.Ranges)
                {
                    if (((range.From != null) && (range.From < 0)) || ((range.To != null) && (range.To > entityLength - 1)))
                        throw new HttpResponseException(System.Net.HttpStatusCode.RequestedRangeNotSatisfiable);
                    item.Ranges.Add(range.From ?? 0, range.To ?? entityLength - 1);
                }
            }
            return item;

        }

        #endregion
        #region ToString

        public override string ToString()
        {
            switch (this.Ranges.Count)
            {
                case 0:
                    return string.Empty;
                case 1:
                    return this.Ranges[0].From.ToString() + "-" + this.Ranges[0].To.ToString();
                default:
                    return "Multiple ranges";
            }
        }

        #endregion
    }
}
